Answers to Sample Prelim 3 Questions
1.
static int[] rightShift ( int[] a )
{
int n = a.length;
int[] b = new int[ n ];
for( int i = 0; i < n; i++ )
b[ i ] = a[ ( n - 1 + i )%n ];
return b;
}
2.
static int[] delete( int[] a, int x )
{
int numOfXs = 0;
for( int i = 0; i < a.length; i++)
if ( a[ i ] == x ) numOfXs++;
int[] b = new int[ a.length - numOfXs
];
for( int i = 0, j = 0; i <
a.length; i++ )
if ( a[ i ] != x )
b[ j++ ] = a[ i ];
return b;
}
3.
static boolean isPalindrome( char[] array
)
{
int i, n = array.length;
for(
i = 0; i < n/2 && ( array[ i ] == array[ n - 1 - i ] ); i++
);
return i == n/2;
}
4.
static int[][] copy( int[][] matrix )
{
int n = matrix.length;
int[][] copy = new int[ n ][ ];
for( int i = 0; i < n; i++ )
{
copy[ i ] = new int[ matrix[ i
].length ];
for( int j = 0; j < matrix[ i
].length; j++ )
copy[ i ][ j ] = matrix[ i ][
j ];
}
return copy;
}
5.
static int[][] rightShift( int[][] matrix
)
{
int n = matrix.length;
int[][] ans = new int[ n ][ matrix[ 0
].length ];
for( int i = 0; i < n; i++ )
for( int j = 0; j < matrix[ i
].length; j++ )
ans[ i ][ j ] = matrix[ ( n -
1 + i )%n ][ j ];
return ans;
}
6.
static double avg( int[][] matrix )
{
int sum = 0, numOfElements = 0;
for( int i = 0; i < matrix.length;
i++ )
for( int j = 0; j < matrix[ i
].length; j++ )
{
sum+=matrix[ i ][ j ];
numOfElements++;
}
return ( (double) sum ) /
numOfElements;
}
Note:
the last solution does not properly handle the case of no input ( a
matrix
of zero size )